const DB = require('../db');
const mongoose = require('mongoose');

async function save(email) {
    return await new DB.Email(email).save()
}


async function queryByIds(emailIds) {
    // let ids = emailIds.map(id => mongoose.Types.ObjectId(id))
    return await DB.Email.find({
            _id: {
                $in: emailIds
            }
        })
        .select();
}

async function query(pageNum = 1, pageCount = 10, filter) {
    pageNum = Number(pageNum);
    pageCount = Number(pageCount);
    return await DB.Email
        .find(filter)
        .limit(pageCount)
        .skip((pageNum - 1) * pageCount)
        .select()

}

async function modify(email) {
    return await DB.Email.update({
        id: email.id
    }, {
        emailAddress: email.emailAddress
    })
}

async function queryAll() {
    return DB.Email.find({
        state: 1
    }).select();
}

async function total() {
    return DB.Email.countDocuments({ state: 1 });
}

async function remove(id) {
    await DB.Keyword.updateMany({
        emailIds: id
    }, { $pull: { emailIds: id } })
    await DB.Email.updateOne({
        _id: id
    }, {
        state: 0
    })
}

module.exports = {
    save,
    query,
    modify,
    queryByIds,
    total,
    queryAll,
    remove
}